import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
// import isPlainObject from 'lodash/isPlainObject'
import store from '@/store'
import notification from 'ant-design-vue/es/notification'
import { ACCESS_TOKEN, ACCEPT_LANGUAGE } from '../store/mutation-types'

const service = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 1000 * 5
})

const err = error => {
  if (error.response) {
    const data = error.response.data
    const token = Vue.ls.get(ACCESS_TOKEN)
    if (error.response.status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message
      })
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      notification.error({
        message: 'Unauthorized',
        description: 'Authorization verification failed'
      })
      if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }
    }
  }
  return Promise.reject(error)
}

// request interceptor
service.interceptors.request.use(config => {
  const token = Vue.ls.get(ACCESS_TOKEN)
  const language = Vue.ls.get(ACCEPT_LANGUAGE)
  if (token) {
    console.log('language', language)
    config.headers['Accept-Language'] = language
    config.headers['Access-Token'] = token
  }
  // 默认参数
  // var defaults = {}
  // 防止缓存，GET请求默认带_t参数
  if (config.method === 'get') {
    config.params = {
      ...config.params,
      ...{ _t: new Date().getTime() }
    }
  }
  // if (isPlainObject(config.params)) {
  //   config.params = {
  //     ...defaults,
  //     ...config.params
  //   }
  // }
  // if (isPlainObject(config.data)) {
  //   config.data = {
  //     ...defaults,
  //     ...config.data
  //   }
  //   if (/^application\/x-www-form-urlencoded/.test(config.headers['content-type'])) {
  //     notification.error({
  //       message: '框架设计遗漏',
  //       description: '/utils/request.js line: 67'
  //     })
  //     // config.data = qs.stringify(config.data)
  //   }
  // }
  return config
}, err)

// response interceptor
service.interceptors.response.use(response => {
  if (response.data.code === 401 || response.data.code === 10001) {
    notification.error({
      message: 'Unauthorized',
      description: 'Authorization verification failed'
    })
    store.dispatch('Logout').then(() => {
      setTimeout(() => {
        window.location.reload()
      }, 1500)
    })
  }
  return response.data
}, err)

const installer = {
  vm: {},
  install(Vue) {
    Vue.use(VueAxios, service)
  }
}

export { installer as VueAxios, service as axios }
